package com.cqupt.utils;

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;

/**
 * 发送命令相关工具类
 **/
public class ActionUtils {

//    Linux操作系统主机
    /**
     * 向主机发送命令
     * @param ip 主机ip
     * @param user 主机账户
     * @param password 主机密码
     * @param command 要发送的命令
     */
    public static String sendCommandToHost(String ip, String user, String password, String command){
        String out = "";
//        String host = "172.22.147.165";
        int port = 22;
//        String user = "zabbix";
//        String password = "zabbix";
//        String command = "mkdir bcd";
        JSch jsch = new JSch();
        Session session = null;
        try {
            session = jsch.getSession(user, ip, port);
            session.setConfig("StrictHostKeyChecking", "no");
            session.setPassword(password);
            session.connect();
            ChannelExec channelExec = (ChannelExec) session.openChannel("exec");
            InputStream in = channelExec.getInputStream();
            channelExec.setCommand(command);
            channelExec.setErrStream(System.err);
            channelExec.connect();
            out = IOUtils.toString(in, "UTF-8");
            channelExec.disconnect();
            session.disconnect();
//            System.out.println(out);
        } catch (JSchException e) {
            e.printStackTrace();
        } catch (IOException e){
            e.printStackTrace();
        }

        return out;
    }

//  window操作系统主机

    /**
     * @param ip 目标主机ip地址
     * @param user 目标主机用户名
     * @param password 目标主机密码
     * @return 结果
     */
    public static Boolean controlWindowHost(String ip,String user,String password){
        try {
            // 清除通道
            Runtime.getRuntime().exec("net use * /del /y");
            // 建立通道
            Process process = Runtime.getRuntime().exec("net use \\\\"+ip+"\\ipc$ \""+password+"\" /user:\""+user+"\"");
            //等待命令执行完
            int i = process.waitFor();
            if (i == 0){
                // 执行命令
                Process result = Runtime.getRuntime().exec("shutdown -s -t 10 -m \\\\"+ip+" -c \"该主机将在10s后被关闭\" -f");
                if(result.waitFor() == 0){
                    return true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
